/**
 * Project: yui3-common-mybatisx
 * Class SoftUpdateBatchById
 * Version 1.0
 * File Created at 2020年3月19日
 * $Id$
 * author yuyi
 * email 1060771195@qq.com
 */
package yui.comn.mybatisx.extension.methods;

import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import yui.comn.mybatisx.core.enums.SoftSqlMethod;
import yui.comn.mybatisx.core.toolkit.SoftConstants;

import java.util.List;

/**
 * <p>
 * 根据ID 批量修改所有值
 * </p>
 *
 * @author yuyi (1060771195@qq.com)
 */
public class SoftUpdateBatch extends AbstractSoftMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        SoftSqlMethod sqlMethod = SoftSqlMethod.UPDATE_BATCH;
        
        // final String additional = optlockVersion(tableInfo) + tableInfo.getLogicDeleteSql(true, true);

        String sqlSetScript = SqlScriptUtils.convertSet(
                SqlScriptUtils.convertIf(
                        SqlScriptUtils.unSafeParam("ew.sqlSet"),
                        String.format("%s != null and %s != null", "ew", "ew.sqlSet"),
                        false));

        String updateScript = String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlSetScript)
                + this.sqlWhereWrapper(true, tableInfo, "ew")
                + SqlScriptUtils.convertChoose(String.format("%s != null and %s != null", "ew", "ew.sqlComment"), SqlScriptUtils.unSafeParam("ew.sqlComment"), "");

        String sql = String.format(SoftSqlMethod.EMPTY.getSql(), SqlScriptUtils.convertForeach(updateScript,
                SoftConstants.COLL, SoftConstants.INDEX, "ew", SEMICOLON));
        
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return addUpdateMappedStatement(mapperClass, List.class, sqlMethod.getMethod(), sqlSource);
    }

}
